﻿<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/view/common/taglibs.jsp"%>

<!DOCTYPE>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <title>新增权限</title>
    <%@ include file="/WEB-INF/view/common/common.jsp"%>
    <script src="${_cdnStaticResourcesPath}/resources/static/js/jquery-fixed.js" type="text/javascript" ></script>
    <script src="${_cdnStaticResourcesPath}/resources/static/js/plugins/validform/Validform.js" type="text/javascript"></script>
    <style>
        .add_style{
            overflow: scroll;
        }
    </style>
</head>
<body>
<div class="clearfix">
    <div id="scrollsidebar" class="left_Treeview" style="margin-right: 10px;">
        <div class="show_btn" id="rightArrow"><span></span></div>
        <div class="widget-box side_content" style="margin-top: 0px;">
            <div class="side_title"><a title="隐藏" class="close_btn"><span></span></a></div>
            <div class="side_list">
                <div class="widget-header header-color-green2">
                    <span style="font-size: 13px;">权限所在的层级（颜色标注）</span>
                </div>
                <div>
                    <div class="widget-main padding-8">
                        <div  id="permissionTree" class="ztree"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div id="category" style="border: 1px solid #dddddd;height: 100%;">
        <div class="type_style" style="height: 100%;">
            <div class="type_title" style="font-size: 14px;">权限详细信息</div>
            <div class="type_content" style="margin-top: 0px;width: 100%;">
                <div class="margin" id="page_style">
                    <div class="add_style" style="float:left;width: 100%;">
                        <form action="${ctx}/permission/updatePermission" method="post" id="form-permission-update">
                            <input des="权限id" type="hidden" value="${permission.id}" name="id" id="id"/>
                            <input des="存放选中的权限id" type="hidden" id="parentId" name="parentId" value="${permission.parentId}"/>
                            <ul>
                                <li class="clearfix" style="margin-top: 0px;">
                                    <div class="alert alert-info" style="text-align: left;margin-top: 0px;margin-bottom: 10px;">
                                        <p>
                                            <i class="fa fa-hand-o-right"></i>&nbsp;当前编辑的
                                            <span style="color: #79B948;font-weight: bold;">
                                                <i class="fa fa-chevron-left"></i>${permission.name}<i class="fa fa-chevron-right"></i>
                                            </span>权限的上级权限是
                                            <span style="font-size: 14px;color: #FF9A3F;font-weight: bold;">
                                                <i class="fa fa-chevron-left"></i><span id="parentPermissionName"></span><i class="fa fa-chevron-right"></i>
                                            </span>
                                        </p>
                                    </div>
                                </li>
                                <li class="clearfix" id="tipLi" style="margin-top: 0px;display: none;">
                                    <div class="alert alert-danger" style="text-align: left;margin-top: 0px;margin-bottom: 10px;">
                                        <p id="tipMsg" style="color: #F72E2E;"></p>
                                    </div>
                                </li>
                                <li class="clearfix">
                                    <label class="label_name" style="text-align: left;;width: 90px;"><i class="c-red">*</i>所属应用：</label>
                                    <div class="formControls col-xs-6">
                                        <span class="select-box" style="width:150px;">
                                            <select class="select col-xs-12" name="appId" id="appId" size="1" style="height: 30px;line-height: 30px;" disabled="disabled">
                                                <c:forEach items="${apps}" var="app">
                                                    <option value="${app.id}" <c:if test="${app.id == permission.appId}">selected="selected"</c:if> >${app.name}</option>
                                                </c:forEach>
                                            </select>
                                        </span>
                                    </div>
                                </li>
                                <li class="clearfix">
                                    <label class="label_name" style="text-align: left;;width: 90px;"><i class="c-red">*</i>权限名称：</label>
                                    <div class="formControls col-xs-6">
                                        <input type="text" placeholder="请输入权限名称" name="name" id="name" autocomplete="off" value="${permission.name}" class="input-text col-xs-12" datatype="*" nullmsg="权限名称不能为空">
                                    </div>
                                    <div class="col-4"> <span class="Validform_checktip"></span></div>
                                </li>
                                <li class="clearfix">
                                    <label class="label_name" style="text-align: left;;width: 90px;"><i class="c-red">*</i>权限描述：</label>
                                    <div class="formControls col-xs-6">
                                        <input type="text" placeholder="请输入权限描述" name="description" id="description" autocomplete="off" value="${permission.description}" class="input-text col-xs-12" datatype="*" nullmsg="权限描述不能为空">
                                    </div>
                                    <div class="col-4"> <span class="Validform_checktip"></span></div>
                                </li>
                                <li class="clearfix">
                                    <label class="label_name" style="text-align: left;;width: 90px;"><i class="c-red">*</i>权限代码：</label>
                                    <div class="formControls col-xs-6">
                                        <input type="text" placeholder="请输入权限代码" name="code" id="code" autocomplete="off" value="${permission.code}" class="input-text col-xs-12" datatype="*" nullmsg="权限代码不能为空">
                                    </div>
                                    <div class="col-4"> <span class="Validform_checktip"></span></div>
                                </li>
                                <li class="clearfix">
                                    <label class="label_name" style="text-align: left;;width: 90px;"><i class="c-red">*</i>权限状态：</label>
                                    <div class="formControls col-xs-6">
                                        <span class="select-box" style="width:150px;">
                                            <select class="select col-xs-12" name="status" size="1" style="height: 30px;line-height: 30px;">
                                                <c:forEach items="${status}" var="s">
                                                    <option value="${s}" <c:if test="${permission.status == s}">selected="selected"</c:if>>${s.description}</option>
                                                </c:forEach>
                                            </select>
                                        </span>
                                    </div>
                                </li>
                                <li class="clearfix">
                                    <div class="alert alert-warning" style="text-align: left;margin-top: 10px;">
                                        <p><i class="fa fa-exclamation-triangle"></i>&nbsp;注意：</p>
                                        <p>1、若您在左侧Tree中变更了当前权限所在的层级），则提交的时候将会更新至数据库中.</p>
                                        <p>2、若只是编辑右侧权限的详情信息，则左侧节点无需操作修改，权限所在的层级不会变更.</p>
                                    </div>
                                </li>
                                <li class="clearfix" style="display: none;">
                                    <div class="col-xs-2 col-lg-2">&nbsp;</div>
                                    <div class="col-xs-9">
                                        <button class="btn btn-primary" type="button" data-loading-text="提交中..." id="btn_submit"><i class="fa fa-save"></i>&nbsp;提交信息</button>
                                    </div>
                                </li>
                            </ul>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<input type="hidden" des="获取对应应用下的权限列表URL" name="getPermissionTreeUrl"  id="getPermissionTreeUrl" value="<c:url value="/permission/getPermissionTree"/>"/>
<input type="hidden" name="permissions" value='${permissions}' des="权限列表json字符串，这里value必须是单引号，避免与permissions值中的双引号冲突，出现问题"/>
</body>
</html>


<script>
    $(document).ready(function() {
        //滚动条美化
        $(".type_style").niceScroll({
            cursorcolor:"#888888",
            cursoropacitymax:1,
            touchbehavior:false,
            cursorwidth:"5px",
            cursorborder:"0",
            cursorborderradius:"5px"
        });
        $("html").css("overflow","auto");
        //当前页面左侧菜单收缩功能
        $("#scrollsidebar").fix({
            float : 'left',
            //minStatue : true,
            skin : 'green',
            spacingw:30,//设置隐藏时的距离
            durationTime :false
        });

        getPermissionTreeData();//获取应用的权限tree数据
    });


    /**
     * tree加载的时候，根据判断，设置与之当前编辑的权限对应的节点的背景色，突出显示
     * @param treeId tree对象的id
     * @param treeNode 每一个node节点对象
     * @returns {{background-color: string}}
     */
    function setFontCss(treeId, treeNode) {
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        var node = treeObj.getNodeByParam("id", $("#id").val(), null);
        if(node != null && treeNode.tId == node.tId){
            if(treeNode.getParentNode() != null){
                $("#" + treeNode.getParentNode().tId + "_a").css("backgroundColor","#FF9A3F").css("color","#fff");//设置父节点的背景颜色
                $("#parentPermissionName").html(treeNode.getParentNode().name);//设置上级权限名称显示
            }else{
                $("#parentPermissionName").html("<span style='color: red;'>（无上级权限）</span>");//设置上级权限名称显示
            }
            return {'background-color':'#79B948','color':'#fff'};//设置当前编辑的权限的节点背景色，突出显示
        }
    }

    function checkPermission() {
        var zTree = $.fn.zTree.getZTreeObj("permissionTree"), type = {"Y" : "ps","N" : "s"};
        zTree.setting.check.chkboxType = type;
    }

    //表单验证提交
    var btn_submit = "#btn_submit";//提交按钮id
    $("#form-permission-update").Validform({
        ajaxPost:true,
        tiptype:2,
        showAllError:true,
        postonce:true, //可选项 表单是否只能提交一次，true开启，不填则默认关闭;
        btnSubmit:btn_submit,
        beforeSubmit:function(curform){
            var selelectParentId = $("#parentId").val();
            var id = $("#id").val();
            if(selelectParentId == id){
                $.message({
                    message:"不能选中自身节点",
                    type:'warning'
                });
                return false;
            }

            if(selelectParentId == -1){
                $("#parentId").val(0);//设置父节点为0，作为顶层菜单。提交到数据库后就是0，而不能是-1，以免造成tree的效果出现瑕疵
            }

            //不能选择子节点作为父节点，因为子节点的parentId已经固定，否则将会出现不知道谁是谁的父节点
            var treeObj = $.fn.zTree.getZTreeObj("permissionTree");
            var nodes=treeObj.getSelectedNodes();//获取选中节点 ztree为树对象
            if (nodes.length > 0) {//循环判断，直到找到根节点
                var node=nodes[0].getParentNode();
                if(node != null && node.id == id){//如果选中子节点作为父节点，这从逻辑上就不对，不能选择子节点作为父节点，只能往上选择
                    $.message({
                        message:"不能选择子节点作为父节点",
                        type:'warning'
                    });
                    return false;
                }
                var bool = false;
                while(node!=null){
                    node=node.getParentNode();
                    if(node==null){
                        break;
                    }
                    if(node!=null && node.id == id){//如果选中子节点作为父节点，这从逻辑上就不对，不能选择子节点作为父节点，只能往上选择
                        bool = true;
                        break;
                    }
                }
                if(bool){
                    $.message({
                        message:"不能选择子节点作为父节点",
                        type:'warning'
                    });
                    return false;
                }
            }
        },
        callback:function(data){
            if(data.code == 200){
                $.message("保存成功");
                getPermissionTreeData();//刷新tree
            }else{
                $.message({
                    message:data.msg,
                    type:'error'
                });
                return false;
            }
            window.parent.getGrid(); //重新加载数据表
        }
    });


    /**
     * 获取应用的权限tree数据
     */
    function getPermissionTreeData(){
        $.ajax({
            url : $("#getPermissionTreeUrl").val(),
            async:true,
            data:{
                "appId" : $("#appId option:selected").val(),//默认获取所属应用下拉框的第一个应用权限数据
                "showTopParent" : false, //是否显示最顶级的节点【无上级权限】
                "open" : false //节点是否展开
            },
            dataType:'json',
            success:function(data,textStatus,jqXHR){
                $("input[name='permissions']").val(data);
                loadTree();
            },
            error:function(xhr,textStatus){}
        });
    }

    function checkPermission() {
        var zTree = $.fn.zTree.getZTreeObj("permissionTree"), type = {"Y" : "ps","N" : "s"};
        zTree.setting.check.chkboxType = type;
    }

    /**
     * 加载权限tree
     */
    var parentIdOld = $("#parentId").val();//保留原始的父节点的ID
    function loadTree(){
        var treeObj;
        var setting = {
            check : {
                enable : false
            },
            data : {
                simpleData : {
                    enable : true
                }
            },
            view: {
                fontCss: setFontCss
            },
            callback : {
                onClick : function(event, treeId, treeNode){//节点被点击后，设置选择的节点id
                    if(parentIdOld != treeNode.id){
                        $("#tipMsg").html("<span style='font-weight: bold;'><i class='fa fa-exclamation-triangle'></i>&nbsp;请注意：当前编辑的权限所在的层级已经被您改变！<br/>"
                                    + "<i class='fa fa-exclamation-triangle'></i>&nbsp;如若没有特殊需要，请勿随意改动，以免影响业务功能！</span><br/>"
                                    + "<span style='color: #000;font-weight: bold;'>最新所在的父节点为：</span><span style='color: #FC8115;font-weight: bold;'>" + treeNode.name + "</span><br/>"
                                    + "<span style='color: #000;font-weight: bold;'>原先所在的父节点为：</span><span style='color: #FC8115;font-weight: bold;'>" + treeObj.getNodeByParam("id", parentIdOld, null).name) + "</span>";
                        $("#tipLi").css("display","block");
                    }else {
                        $("#tipMsg").html("");
                        $("#tipLi").css("display","none");
                    }
                    $("#parentId").val(treeNode.id);
                }
            }
        };
        var roles = $("input[name='permissions']").val();
        $.fn.zTree.init($("#permissionTree"), setting, eval("(" + roles + ")"));
        checkPermission();


        //默认选中权限的父亲节点
        treeObj = $.fn.zTree.getZTreeObj("permissionTree");
        var nodes = treeObj.getCheckedNodes(false);
        var parentId = $("#parentId").val();
        if (nodes.length>0) {
            for(var i = 0; i < nodes.length; i++){
                if(parentId == 0){//说明是最顶层的菜单，则选中最顶级的节点[无上级权限]
                    if(nodes[i].id == -1){
                        treeObj.selectNode(nodes[i]);
                        break;
                    }
                }else{
                    if(nodes[i].id == parentId){
                        treeObj.selectNode(nodes[i]);
                        break;
                    }
                }
            }
        }

        var treeObj = $.fn.zTree.getZTreeObj("permissionTree");
        var selectPermissionId = $("#id").val();//当前权限id
        if(selectPermissionId != ""){
            var selectNode = treeObj.getNodeByParam("id", selectPermissionId, null);//获取当前权限的节点
            expandAllParentNode(treeObj,selectNode);//展开当前节点的所有父节点
        }
    }

    /**
     * 展开当前节点的所有父节点
     */
    function expandAllParentNode(treeObj,selectNode) {
        var parentNode = selectNode.getParentNode();
        if(parentNode != undefined && parentNode != null){
            treeObj.expandNode(parentNode,true, false);//指定选中ID节点展开
            expandAllParentNode(treeObj,parentNode);
        }
    }
</script>
